﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Microsoft.SharePoint.Administration;
using System.Windows;
using Microsoft.SharePoint;

namespace SharePointCommander.Model.TreeView
{
    public class SCWebApplication : SCTreeViewItem<SPWebApplication>
    {
        public SCWebApplication(SCTreeViewItem parent, SPWebApplication webApplication)
            : base(parent, webApplication)
        {
            if (string.IsNullOrEmpty(webApplication.DisplayName))
            {
                Header = webApplication.Id.ToString();
            }
            else
            {
                Header = webApplication.DisplayName;
            }
            IsExpanded = false;
            Expanded += new RoutedEventHandler(SCWebApplication_Expanded);
            ItemsSource = new object[] { null };
        }

        void SCWebApplication_Expanded(object sender, System.Windows.RoutedEventArgs e)
        {
            TreeViewItem item = e.Source as TreeViewItem;
            if (item.ItemsSource.Cast<object>().Contains(null))
            {
                var runningJobsNode = new SCTreeViewItem<SPRunningJobCollection>(this, SPObject.RunningJobs)
                {
                    Header = "Running Jobs"
                };
                runningJobsNode.ItemsSource = from SPRunningJob runningJob in SPObject.RunningJobs select new SCTreeViewItem<SPRunningJob>(runningJobsNode, runningJob);

                item.ItemsSource = new[] { 
                            new SCSiteCollection(this, SPObject.Sites) as TreeViewItem,
                            new SCApplicationPool(this, SPObject.ApplicationPool) as TreeViewItem,
                            new SCContentDatabaseCollection(this, SPObject.ContentDatabases) as TreeViewItem,
                            new SCJobDefinitionCollection(this, SPObject.JobDefinitions) as TreeViewItem,
                            runningJobsNode,
                            new SCProperties(this, SPObject.Properties) as TreeViewItem
                        };
            }
        }
    }
}
